package com.inspectortime.webapp.inspector.fee;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class FeeWizardAdjustersController implements Controller {

	private Repository repository;
	
	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// Helper being used to store form fields		
		FeeWizardCommonHelper helper = FeeUtils.retrieveWizardCommonHelperFromSession(request);
		
		if (request.getMethod().equalsIgnoreCase("get")) {
			ModelAndView mv = new ModelAndView("inspector/fee/feeWizardAdjusters");
			
			// Set default center zip code to company's zip code
			InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
			if (helper.getDistanceInMilesCenterZip() == null) {
				helper.setDistanceInMilesCenterZip(company.getAddress().getZipCode());	
			}
			mv.addObject("helper", helper);
			return mv;
		}
		
		// POST

		// Collect values
		String newCenterZip = request.getParameter("distanceInMilesCenterZip");		
		if (newCenterZip.length() > 2) {
			helper.setDistanceInMilesCenterZip(newCenterZip);
		}
		
		String newIncrease = request.getParameter("distanceInMilesFeeIncreasePerMile");
		helper.setDistanceInMilesFeeIncreasePerMile(Double.parseDouble(newIncrease));
		
		String newLimit = request.getParameter("distanceInMilesLimit");
		helper.setDistanceInMilesLimit(Integer.parseInt(newLimit));
		
		String viewName = "feeWizardConfirmSave.html";
		ModelAndView mv = new ModelAndView("redirect:" + viewName);
		return mv;
	}

}
